package com.taplinker.client.crm.rpc;

import android.widget.Toast;

import com.google.protobuf.InvalidProtocolBufferException;
import com.taplinker.client.AppConfigContext;
import com.taplinker.client.crm.domain.CrmDataCenter;
import com.taplinker.client.crm.domain.CustomerInfo;
import com.taplinker.core.rpc.Result;
import com.taplinker.core.rpc.command.SimpleBaseCommand;
import com.taplinker.core.rpc.http.HttpTemplate;
import com.taplinker.dto.web.ActionCusRequestProto;
import com.taplinker.dto.web.ActionCusRequestProto.ActionCusRequest.Builder;
import com.taplinker.dto.web.ActionCusRequestProto.ActionCusRequestType;
import com.taplinker.dto.web.ActionProto.Action;

/**
 * 获取用户的时间轴
 * @author djbian
 *
 */
public class GetClientTimeLine extends SimpleBaseCommand {

	private ActionCusRequestType type;
	private CustomerInfo info;
	public GetClientTimeLine(ActionCusRequestType type, CustomerInfo info) {
		this.type = type;
		this.info = info;
	}
	
	public GetClientTimeLine(CustomerInfo info) {
		this.type = ActionCusRequestType.ALL;
		this.info = info;
	}
	@Override
	public Result go() {
		Builder b = ActionCusRequestProto.ActionCusRequest.newBuilder();
		b.setType(type);
		if(info.getCustomer() == null) {
			b.setVisitorId(info.getVisitorId());
		} else {
			b.setVisitorId(info.getCustomer().getVistorId());
		}
		b.setEndDate("");
		if(info != null&& info.getClientAction().size()>0) {
			b.setEndDate(String.valueOf(info.getClientAction().get(info.getClientAction().size()-1).getDate()));
		}
		b.setLimit(10);
		return new HttpTemplate().postForGogoByte(AppConfigContext.TAPLINKER_WEB
				+ "/services/crm/v1/action/customerservice",
				b.build().toByteArray());
	}
	 
	@Override
	public void yes(Result result) {
		super.yes(result);
		try {
			Action action = Action.parseFrom((byte[]) result.object);
			info.addClientAction(action.getCsActionList());
			CrmDataCenter.getInstance().noticeListener(CrmDataCenter.GET_CLIENT_TIME);
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
			Toast.makeText(context, "" + result.message, Toast.LENGTH_SHORT).show();
		}
	}
}